package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.LgAutowried;
import com.lagou.edu.mvcframework.annotations.LgController;
import com.lagou.edu.mvcframework.annotations.LgRequestMapping;
import com.lagou.edu.mvcframework.annotations.LgService;
import com.lagou.edu.mvcframework.pojo.HandlerMapping;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 功能描述
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2021-5-30 23:01
 */
public class LgDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    //缓存所有扫描到的类的全限定类名
    private List<String> classNameList = new ArrayList<>();

    //存初始完成的类信息
    Map<String,Object> iocMap = new HashMap<>();

    //存储URL和Method的映射关系
    //Map<String,Method> handlerMapping = new HashMap<>();

    List<HandlerMapping> handlerMappingList = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2、扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        //3、初始化bean对象（实现IOC容器，基于注解的方式）
        doInstance();
        //4、实现依赖注入
        doAutoWired();
        //5、构建一个initHandlerMapping处理器，将配置好的url和method建立映射关系
        initHandlerMapping();
        System.out.println("lagou mvc 初始化完成...");
        //6、等待请求进入，处理请求
    }

    /**
     * 构造一个HandlerMapping映射器处理器
     * 将配置好的URL和Method建立映射关系
     */
    private void initHandlerMapping() {
        //1、从IOC容器当中获取到所有带有LgController的类信息
        if(iocMap == null || iocMap.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            //如果类中没有LgControlle注解，则说明该类不是Controller信息，不进行处理
            if(!aClass.isAnnotationPresent(LgController.class)){continue;}

            //如果是Controlle类，需要判断类上面是否有LgRequestMapping信息
            String baseUrl = "";
            if(aClass.isAnnotationPresent(LgRequestMapping.class)){
                baseUrl = aClass.getAnnotation(LgRequestMapping.class).value();
            }

            //获取类中的所有方法，判断方法上面是否有LgRequestMapping信息，\
            // 如果有就和baseUrl拼接获取到实际的URL信息，并建立映射关系
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(LgRequestMapping.class)){continue;}
                LgRequestMapping annotation = method.getAnnotation(LgRequestMapping.class);
                String methodUrl = annotation.value();

                HandlerMapping handlerMapping = new HandlerMapping(entry.getValue(),method, Pattern.compile(baseUrl+methodUrl));

                //判断方法的参数名称信息，如果是HttpServletRequest或是HttpServletResponse就需要做特殊的处理
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    if(parameters[i].getType() == HttpServletRequest.class
                        || parameters[i].getType() == HttpServletResponse.class ){
                        handlerMapping.getParamInfo().put(parameters[i].getType().getSimpleName(),i);
                    } else {
                        handlerMapping.getParamInfo().put(parameters[i].getName(),i);
                    }
                }
                handlerMappingList.add(handlerMapping);
            }
        }
    }

    /**
     * 通过反映对初始化完成的类进行依赖注入处理
     */
    private void doAutoWired() {
        if(iocMap == null || iocMap.isEmpty()){return;}

        for(Map.Entry<String,Object> entry:iocMap.entrySet()){
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if(!declaredField.isAnnotationPresent(LgAutowried.class)){
                    continue;
                }

                //如果包含有注解信息，就需要做依赖注入操作
                LgAutowried annotation = declaredField.getAnnotation(LgAutowried.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())){
                    //如果LgAutowried上面没有名称，则需要通过接口来进行注入
                    beanName = declaredField.getType().getName();
                }
                //设置强制访问类的属性
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),iocMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 根据扫描到的类信息和注解信息，对类进行初始化操作,初始化完成之后放到IOC容器当中
     */
    private void doInstance() {
        if(classNameList == null || classNameList.isEmpty()){
            return;
        }

        try {
            for (int i = 0; i < classNameList.size(); i++) {
                String className = classNameList.get(i);
                //通过反映获取到类信息
                Class<?> aClass = Class.forName(className);
                //区分当前类是Controller还是Service
                if(aClass.isAnnotationPresent(LgController.class)){
                    //将控制器以首字母小写保存到IOC容器当中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstName = lowerFirst(simpleName);
                    iocMap.put(lowerFirstName,aClass.newInstance());
                } else if(aClass.isAnnotationPresent(LgService.class)){
                    LgService annotation = aClass.getAnnotation(LgService.class);
                    //获取设置到注解当中的value值
                    String beanName = annotation.value();
                    if(!"".equals(beanName.trim())){
                        iocMap.put(beanName,aClass.newInstance());
                    } else {
                        String simpleName =  lowerFirst(aClass.getSimpleName());
                        iocMap.put(simpleName,aClass.newInstance());
                    }

                    //Service层一般都有接口，此处需要再根据当前类实现的接口信息再存放一份到IOC容器当中，
                    // 方便后期可以根据接口类型进行注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    if(interfaces == null || interfaces.length > 0){
                        return;
                    }

                    for (Class<?> anInterface : interfaces) {
                        iocMap.put(anInterface.getName(),aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将字符串的首字母小写
     * @param simpleName
     * @return
     */
    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if(chars[0] >= 'A' && chars[0] <= 'Z' ){
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * 根据路径，递归处理扫描到的所有类信息，并将类信息添加到List当中做缓存处理
     * @param scanPackage
     */
    private void doScan(String scanPackage) {
        String scanPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+
                scanPackage.replaceAll("\\.", "/");
        File files = new File(scanPath);
        File[] listFiles = files.listFiles();
        for (File listFile : listFiles) {
            if(listFile.isDirectory()){
                doScan(scanPackage+"."+listFile.getName());
            } else if(listFile.getName().endsWith(".class")){
                String className = scanPackage+"."+listFile.getName().replace(".class", "");
                classNameList.add(className);
            }
        }
    }


    /**
     * 根据配置文件路径加载配置文件信息
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //通过请求路径获取到具体需要调用的method方法

        //此处由于method.invoke方法需要传入对应的方法的具体的类名信息，简单的通过Map的形式存储的handlerMapping满足不了需求，所以
        // 需要创建HandlerMapping类进行属性封装
        //Method method = handlerMapping.get(requestURI);
        //method.invoke()

        //获取当前的请求处理Handler
        HandlerMapping handler = getHandler(req);
        if(handler == null){
            return;
        }

        //获取当前请求方法所有的参数信息
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上述参数类型长度定义参数信息，参数的长度和参数类型的长度一致
        Object[] paramValues = new Object[parameterTypes.length];
        //获取到所有的参数
        Map<String,String[]> parameterMap = req.getParameterMap();
        //将参数组装到paramValues当中，而且需要保证参数的位置和形参的顺序一致
        for (Map.Entry<String,String[]> param : parameterMap.entrySet()) {
            String paramKey = param.getKey();
            String value = StringUtils.join(Arrays.asList(param.getValue()), ",");
            //如果参数和方法中的参数匹配上了，就填充数据
            if(!handler.getParamInfo().containsKey(paramKey)){continue;}
            //获取参数对应的位置信息
            Integer paramIndex = handler.getParamInfo().get(paramKey);
            //填充对应的参数值信息
            paramValues[paramIndex] = value;
        }

        //处理HttpServletRequest和HttpServletResponse参数
        Integer requestIndex = handler.getParamInfo().get(HttpServletRequest.class.getSimpleName());
        if(null != requestIndex){
            paramValues[requestIndex] = req;
        }

        Integer responseIndex = handler.getParamInfo().get(HttpServletResponse.class.getSimpleName());
        if(null != responseIndex){
            paramValues[responseIndex] = resp;
        }


        try {
            handler.getMethod().invoke(handler.getController(),paramValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private HandlerMapping getHandler(HttpServletRequest request) {
        //获取到请求路径信息
        String requestURI = request.getRequestURI();
        if(handlerMappingList == null || handlerMappingList.isEmpty()){
            return null;
        }
        for (HandlerMapping handlerMapping : handlerMappingList) {
            Matcher matcher = handlerMapping.getUrl().matcher(requestURI);
            if(!matcher.matches()){continue;}
            return handlerMapping;
        }
        return null;
    }
}
